package com.example.bottom.sheet;

import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.bottom.R;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/***
 * 有个坑，如果超出高度了，重新设置高度，下方会出现空白
 */
public class BottomSheet1Activity extends AppCompatActivity {

    //最大高度
    private int maxHeight;
    //上边距
    private int marginTop;

    private BottomSheetBehavior mBottomSheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_sheet1);
        //填充rv
        RecyclerView rv = findViewById(R.id.recyclerView);
        rv.setItemAnimator(new DefaultItemAnimator());
        rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        Adapter adapter = new Adapter();
        rv.setAdapter(adapter);
        //fab的容器
        final LinearLayout fabContainer = findViewById(R.id.fab_container);
        //搜索  文本
        final TextView tv = findViewById(R.id.tv1);
        //获取屏幕的高度
        final int heightPixels = getResources().getDisplayMetrics().heightPixels;
        //actionbar的高度
        final ActionBar bar = getSupportActionBar();
        tv.post(new Runnable() {
            @Override
            public void run() {
                CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) tv.getLayoutParams();

                //获取状态栏的高度
                int statusBarHeight = 0;
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                }
                //输入框至屏幕顶部的高度
                marginTop = tv.getHeight() + lp.topMargin + lp.bottomMargin / 2;
                //底部列表的最大高度
                maxHeight = heightPixels - statusBarHeight - bar.getHeight() - marginTop;
//                Log.i("zxd", "maxHeight: " + maxHeight);
//                Log.i("zxd", "marginTop: " + marginTop);
            }
        });

        final int peekHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());


        NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView);
        mBottomSheetBehavior = BottomSheetBehavior.from(nestedScrollView);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View view, int i) {
                if (i != BottomSheetBehavior.STATE_DRAGGING) {
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    Log.i("zxd", "onStateChanged: " + view.getHeight());
                    if (view.getHeight() > maxHeight) {
                        //如果滑动的高度覆盖了 搜索文本，滑动到文本之下

//                        view.setTranslationY(marginTop);
//                        Log.i("zxd", "getTop: " + view.getTop());
//                        Log.i("zxd", "getBottom: " + view.getBottom());
                        Log.i("zxd", "getY: " + view.getY());

                        //1.禁用掉NestedScrollView的滑动(无效)
                        //在rv里设置xml属性为android:nestedScrollingEnabled="false"
                        //
                        //2.滑动下
                        //3.rv也设置高度(无效)


                        layoutParams.height = maxHeight;
                        view.setLayoutParams(layoutParams);


                        /*ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                        params.bottomMargin = 0;
                        view.requestLayout();
                        view.postInvalidate();*/


//                        view.setY(view.getY() + marginTop);

                        //因为view滑过载了，设置了view的高度，导致下方出现空白

//                        view.scrollTo(view.getTop(), -marginTop);
                    }
                } else {
                    //出现bug的原因在等于就需要给他设置高度
                    if (view.getHeight() >= maxHeight) {
                        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                        layoutParams.height = maxHeight;
                        view.setLayoutParams(layoutParams);
                    }
                }
            }

            @Override
            public void onSlide(@NonNull View view, float v) {
                //从折叠到打开，0-1。反过来是1-0
                //从折叠到隐藏，0到-1，反过来是-1到0
                float distance;
                if (v > 0) {//在peekHeight位置以上 滑动(向上、向下) slideOffset bottomSheet.getHeight() 是展开后的高度的比例
                    distance = view.getHeight() * v;
                } else {//在peekHeight位置以下 滑动(向上、向下)  slideOffset 是PeekHeight的高度的比例
                    distance = mBottomSheetBehavior.getPeekHeight() * v;
                }
                if (distance < 0) {
                    //向下移动，当NestedScrollView完全隐藏的时候
                    fabContainer.setTranslationY(-distance);
                } else {
                    if (distance <= peekHeight) {
                        fabContainer.setTranslationY(-distance);
                    }
                }
                Log.e("zxd", String.format("slideOffset -->>> %s bottomSheet.getHeight() -->>> %s heightPixels -->>> %s", v, view.getHeight(), heightPixels));
            }
        });
    }

    static class Adapter extends RecyclerView.Adapter<Adapter.Holder> {

        private Adapter.OnItemClickListener mItemClickListener;

        public void setOnItemClickListener(Adapter.OnItemClickListener li) {
            mItemClickListener = li;
        }

        @Override
        public Adapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
            return new Adapter.Holder(item);
        }

        @Override
        public void onBindViewHolder(final Adapter.Holder holder, int position) {
            holder.tv.setText("item " + position);
            if (mItemClickListener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mItemClickListener.onItemClick(holder.getLayoutPosition(),
                                holder.tv.getText().toString());
                    }
                });
            }
            holder.iv.setImageResource(R.drawable.b1);
        }

        @Override
        public int getItemCount() {
            return 50;
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView tv;
            ImageView iv;

            public Holder(View itemView) {
                super(itemView);
                tv = itemView.findViewById(R.id.txt_title);
                iv = itemView.findViewById(R.id.img_Pic);
            }
        }

        interface OnItemClickListener {
            void onItemClick(int position, String text);
        }
    }
}